package cool.houge.pig.infra.service.login;

import cool.houge.pig.BizErrors;
import cool.houge.pig.StacklessBizCodeException;
import cool.houge.pig.model.LoginChannel;
import cool.houge.pig.repository.login.LoginChannelRepository;
import cool.houge.pig.service.login.LoginChannelAuthentication;
import java.util.Objects;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * 基础认证.
 *
 * @author KK (kzou227@qq.com)
 */
@Component
public class BasicLoginChannelAuthentication implements LoginChannelAuthentication {

  private final LoginChannelRepository loginChannelRepository;

  public BasicLoginChannelAuthentication(LoginChannelRepository loginChannelRepository) {
    this.loginChannelRepository = loginChannelRepository;
  }

  @Override
  public Mono<LoginChannel> authenticate(String key, String passphrase) {
    return loginChannelRepository
        .findByChannelKey(key)
        .doOnNext(
            loginChannel -> {
              if (!Objects.equals(loginChannel.getChannelPassphrase(), passphrase)) {
                throw new StacklessBizCodeException(BizErrors.C1301, "口令不匹配");
              }
            })
        .switchIfEmpty(Mono.error(() -> new StacklessBizCodeException(BizErrors.C1301, "未找到登录通道")));
  }
}
